package data

import (
	"html"
	"html/template"

	"gitee.com/xchengli/blog-lib/database"
	"gitee.com/xchengli/blog-lib/zlog"

	"github.com/gin-gonic/gin"
)

type OptDataService struct{}

// Opt 配置项
type Opt struct {
	ID          int64         `json:"id"`
	AreaCode    string        `json:"area_code"`
	Key         string        `json:"key"`
	Title       template.HTML `json:"title"`
	Description template.HTML `json:"description"`
	Value       string        `json:"value"`
	RelationID  int64         `json:"relation_id"`
	Sort        int64         `json:"sort"`
	Extension   string        `json:"extension"`
	CreateTime  string        `json:"create_time"`
	UpdateTime  string        `json:"update_time"`
}

// Opts 配置项列表
type Opts []Opt

// GetAll 获取所有配置
func (s *OptDataService) GetAll(ctx *gin.Context) (Opts, error) {
	var opts Opts
	db := database.GetDB()

	rows, err := db.Table("bg_opt").
		Select("id, area_code, key, title, description, value, relation_id, sort, extension, create_time, update_time").
		Rows()
	if err != nil {
		zlog.Error(ctx, err)
		return opts, err
	}
	defer rows.Close()

	for rows.Next() {
		var opt Opt
		var title, description string

		err := rows.Scan(&opt.ID, &opt.AreaCode, &opt.Key, &title, &description, &opt.Value, &opt.RelationID, &opt.Sort, &opt.Extension, &opt.CreateTime, &opt.UpdateTime)
		if err != nil {
			zlog.Error(ctx, err)
			continue
		}

		opt.Title = template.HTML(html.UnescapeString(title))
		opt.Description = template.HTML(html.UnescapeString(description))

		opts = append(opts, opt)
	}

	return opts, nil
}

// GetAllAbout 获取关于页面的配置
func (s *OptDataService) GetAllAbout(ctx *gin.Context) (Opts, error) {
	var opts Opts
	db := database.GetDB()

	rows, err := db.Table("bg_opt").
		Select("id, area_code, key, title, description, value, relation_id, sort, extension, create_time, update_time").
		Where("area_code = ?", "about").
		Order("sort DESC").
		Rows()
	if err != nil {
		zlog.Error(ctx, err)
		return opts, err
	}
	defer rows.Close()

	for rows.Next() {
		var opt Opt
		var title, description string

		err := rows.Scan(&opt.ID, &opt.AreaCode, &opt.Key, &title, &description, &opt.Value, &opt.RelationID, &opt.Sort, &opt.Extension, &opt.CreateTime, &opt.UpdateTime)
		if err != nil {
			zlog.Error(ctx, err)
			continue
		}

		opt.Title = template.HTML(html.UnescapeString(title))
		opt.Description = template.HTML(html.UnescapeString(description))

		opts = append(opts, opt)
	}

	return opts, nil
}
